from django.contrib import admin
from backup.models import BackupConfig, BackupConfigRecord, BackupRecord
import os
from django.utils import timezone


@admin.register(BackupConfig)
class BackupConfigAdmin(admin.ModelAdmin):

    actions = ['do_backup']

    def save_model(self, request, obj, form, change):
        obj.save(create_uid=request.user.id)

    def do_backup(self, request, queryset):
        """
        执行备份
        """
        user_id = request.user.id
        for obj in queryset:
            print(obj.name)
            print(obj.storage_instance.type)
            print(obj.db_instance.host)
            print(obj.db_instance.username)
            print(obj.db_instance.password)
            print(obj.db_instance.database_name)
            print(obj.backup_path)

            host = obj.db_instance.host
            username = obj.db_instance.username
            password = obj.db_instance.password
            port = 3306
            database_name = obj.db_instance.database_name
            backup_path = obj.backup_path

            if not os.path.exists('./dbdump'):
                os.mkdir('dbdump')

            if not os.path.exists(backup_path):
                os.mkdir(backup_path)

            ARCHIVE = 'ggac_' + timezone.datetime.now().strftime("%Y%m%d%H%M%S") + '.sql.gz'
            cmd = f"mysqldump -h {host} -u {username} -P {port} -p{password} -q -Q --set-gtid-purged=OFF --default-character-set=utf8 --skip-lock-tables {database_name} 2>ggac.err | gzip > {backup_path}{ARCHIVE}"
            print(cmd)
            os.system(cmd)

            if obj.storage_instance.type == 1:
                pass

            backup_record_obj = BackupRecord.objects.create(
                create_uid=user_id,
                backup_config_id=obj.id,
                storage_instance_id=obj.storage_instance_id,
                db_instance_id=obj.db_instance_id,
                backup_filepath=obj.backup_path + ARCHIVE,
            )
            backup_record_obj.save()

    do_backup.short_description = "执行备份"


@admin.register(BackupConfigRecord)
class BackupConfigRecordAdmin(admin.ModelAdmin):
    list_display = ['create_date', 'create_uid', 'backup_config_id', 'storage_instance_id', 'db_instance_id']
    list_filter = ['backup_config_id']


@admin.register(BackupRecord)
class BackupRecordAdmin(admin.ModelAdmin):
    list_display = ['create_date', 'create_uid', 'backup_config_id', 'storage_instance_id', 'db_instance_id']
    list_filter = ['backup_config_id']
